package cn.openea.perpartner.meily.web.entity.dto;

import cn.hutool.core.util.StrUtil;
import cn.openea.perpartner.common.core.annotation.Excel;
import cn.openea.perpartner.common.core.utils.StringUtils;
import cn.openea.perpartner.meily.web.entity.GroupBuyingSub;
import cn.openea.perpartner.meily.web.entity.Provider;
import cn.openea.perpartner.meily.web.service.IProviderService;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

/**
 * (GroupBuyingSub)DTO
 *
 * @author rains
 * @since 2023-02-06 16:25:59
 */
@Component
public class GroupBuyingSubDTOFactory {

    @Resource
    private IProviderService providerService;


    /**
     * 团购订单详情DTO
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @SuperBuilder
    public static class DetailsDto {
        private String id;
        @ApiModelProperty(value = "工单号")
        private String taskNumber;
        @ApiModelProperty(value = "创建时间")
        private String createTime;
        @ApiModelProperty(value = "更新时间")
        private String updateTime;
        @ApiModelProperty(value = "主文档ID")
        private String mainDocunid;
        @ApiModelProperty(value = "参与者id")
        private String partnerId;
        @ApiModelProperty(value = "参与者昵称")
        private String partnerName;
        @ApiModelProperty(value = "参与者头像")
        private String partnerAvatarUrl;
        @ApiModelProperty(value = "单价")
        private String unitPrice;
        @ApiModelProperty(value = "购买数量")
        private String buyQuantity;
        @ApiModelProperty(value = "支付金额")
        private String payAmount;
        @ApiModelProperty(value = "参与团购时间")
        private String joinTime;
        @ApiModelProperty(value = "商品记录唯一ID")
        private String goodsId;
        @ApiModelProperty(value = "商品编号")
        private String goodsNo;
        @ApiModelProperty(value = "商品名称")
        private String goodsName;
        @ApiModelProperty(value = "定制ID")
        private String sceneAssetsId;
        @ApiModelProperty(value = "场景ID")
        private String sceneId;
        @ApiModelProperty(value = "状态。0:未参与；1:已参与；(默认1)")
        private String status;
        @ApiModelProperty(value = "支付订单ID")
        private String orderId;
        @ApiModelProperty(value = "订单状态：已付款、已发货、已完成、已退款；(默认已付款)")
        private String orderStatus;
        @ApiModelProperty(value = "发货时间")
        private String deliveryTime;
        @ApiModelProperty(value = "确认收货时间")
        private String receivingTime;
        @ApiModelProperty(value = "退款订单号")
        private String refundNo;
        @ApiModelProperty(value = "退款金额")
        private String refundAmount;
        @ApiModelProperty(value = "退款时间")
        private String refundTime;
        @ApiModelProperty(value = "物流公司名称")
        private String courierName;
        @ApiModelProperty(value = "物流单号")
        private String courierNumber;
        @ApiModelProperty(value = "周期串")
        private String cycle;
        @ApiModelProperty(value = "供货商编号")
        private String supplierId;
        @ApiModelProperty(value = "供货商名称")
        private String supplierName;
        @ApiModelProperty(value = "供货商(JSONObject对象)")
        private String supplier;
        @ApiModelProperty(value = "商品规格")
        private String specification;
        @ApiModelProperty(value = "分享验证id")
        private String shareValidationId;
        @ApiModelProperty(value = "是否发放分享奖励")
        private String sendShareRewards;
        @ApiModelProperty(value = "是否发放团销奖励")
        private String sendGroupSalesRewards;
        @ApiModelProperty(value = "分享图片的路径")
        private String sharePictureUrl;
        @ApiModelProperty(value = "线上服务商id")
        private String initiatorId;
        @ApiModelProperty(value = "线上服务商昵称")
        private String initiatorName;
        @ApiModelProperty(value = "标记颜色")
        private String markColor;
        @ApiModelProperty(value = "订单备注")
        private String orderRemarks;
        @ApiModelProperty(value = "收货人姓名")
        private String consigneeName;
        @ApiModelProperty(value = "手机号码")
        private String consigneePhoneNum;
        @ApiModelProperty(value = "收货地址")
        private String consigneeAddress;
        @ApiModelProperty(value = "收货地址")
        private String address;
        @ApiModelProperty(value = "发货链接")
        private String shippingLink;
        @ApiModelProperty(value = "供货价")
        private BigDecimal supplyPrice = BigDecimal.ZERO;
        @ApiModelProperty(value = "延迟收货天数")
        private Integer delayedReceiptDays;
        private Provider onlineProvider; // 团长的信息
        private Provider offlineProvider; // 店铺服务商信息
        @ApiModelProperty("商品品牌")
        private String goodsBrand;
        @ApiModelProperty("商品分类三级") // TODO 先这样处理后面在去改数据
        private List<String> goodsCategoryList;
        @ApiModelProperty("商品分类")
        private String goodsCategory;
        @ApiModelProperty(name = "真实供货价")
        private BigDecimal realSupplyPrice;
        @ApiModelProperty(name = "地址信息是否更改")
        private boolean addressInfoChange = false;
        @ApiModelProperty(name = "实物")
        private String entity;
        @ApiModelProperty(name = "快递公司编码")
        private String expressCompanyCode;
        @ApiModelProperty(name = "优惠券金额")
        private BigDecimal couponAmount;
        @ApiModelProperty("钱包抵扣金额")
        @Builder.Default
        private BigDecimal deductionAmount = BigDecimal.ZERO;
        @ApiModelProperty("应付金额")
        @Builder.Default
        private BigDecimal originalPayAmount = BigDecimal.ZERO;
    }

    public Function<GroupBuyingSub, DetailsDto> toDetailsDto = (groupBuyingSub) -> {
        if (groupBuyingSub == null) {
            return null;
        }
        DetailsDto detailsDto = new DetailsDto();
        BeanUtils.copyProperties(groupBuyingSub, detailsDto);
        // 拆分收货地址
        String address = groupBuyingSub.getAddress();
        JSONObject addressObj = new JSONObject();
        if (StrUtil.isNotBlank(address)) {
            addressObj = JSONObject.parseObject(address);
        }
        if (!addressObj.isEmpty()) {
            detailsDto.setConsigneeName(addressObj.getString("Name"));
            detailsDto.setConsigneePhoneNum(addressObj.getString("PhoneNum"));
            // 处理收获地址
            String streetVillage = addressObj.getString("StreetVillage");
            int location = streetVillage.indexOf('-');
            String consigneeAddress = "";
            if (StringUtils.isNotBlank(streetVillage) && location != -1) {
                consigneeAddress = addressObj.getString("Region") + "\t" + streetVillage.substring(0, location) + addressObj.getString("Address");
            } else {
                consigneeAddress = addressObj.getString("Region") + "\t" + streetVillage + addressObj.getString("Address");
            }
            detailsDto.setConsigneeAddress(consigneeAddress); // 收货地址
            detailsDto.setAddressInfoChange(addressObj.getBoolean("InfoChange") != null);
        }
        // 处理区域服务商
        String supplier = groupBuyingSub.getSupplier();
        if (StrUtil.isNotBlank(supplier)) {
            detailsDto.setOfflineProvider(JSONObject.parseObject(supplier, Provider.class));
        }
        if (StringUtils.isNotBlank(groupBuyingSub.getInitiatorId())) {
            detailsDto.setOnlineProvider(providerService.getByUserId(groupBuyingSub.getInitiatorId()));
        }
        // 处理商品分类
        detailsDto.setGoodsCategoryList(Arrays.asList(groupBuyingSub.getGoodsCategory().split("-")));
        return detailsDto;
    };

    /**
     * 导出Excel模板DTO
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @SuperBuilder
    public static class ExportExcelTemplateDto {
        @Excel(name = "订单编号")
        private String orderId;
        @Excel(name = "订单状态")
        private String orderStatus;
        @Excel(name = "交易时间")
        private String joinTime;
        @Excel(name = "实物")
        private String entity;
        @Excel(name = "收货人")
        private String consigneeName;
        @Excel(name = "手机号")
        private String consigneePhoneNum;
        @Excel(name = "商品名称")
        private String goodsName;
        @Excel(name = "发货链接")
        private String shippingLink;
        @Excel(name = "商品规格")
        private String specification;
        @Excel(name = "玫丽价")
        private String unitPrice;
        @Excel(name = "供货价")
        private BigDecimal supplyPrice = BigDecimal.ZERO;
        @Excel(name = "实际供货价")
        private BigDecimal realSupplyPrice;
        @Excel(name = "购买数量")
        private String buyQuantity;
        @Excel(name = "实付金额")
        private String payAmount;
        @Excel(name = "订单备注")
        private String orderRemarks;
        @Excel(name = "收货地址")
        private String consigneeAddress;
        @Excel(name = "物流公司名称")
        private String courierName;
        @Excel(name = "物流单号")
        private String courierNumber;
        @Excel(name = "消费者")
        private String partnerName;
        @Excel(name = "代理服务商")
        private String onlineProviderInfo;
        @Excel(name = "选址服务商")
        private String offlineProviderInfo;
    }

    public Function<GroupBuyingSub, ExportExcelTemplateDto> toExportExcelTemplateDto = (groupBuyingSub) -> {
        if (groupBuyingSub == null) {
            return null;
        }
        DetailsDto detailsDto = toDetailsDto.apply(groupBuyingSub);
        ExportExcelTemplateDto excelTemplateDto = new ExportExcelTemplateDto();
        BeanUtils.copyProperties(detailsDto, excelTemplateDto);
        // 处理下数据的状态
        if ("已付款".equals(groupBuyingSub.getOrderStatus())) {
            excelTemplateDto.setOrderStatus("待发货");
        }
        // 处理选址区域服务商
        String supplier = groupBuyingSub.getSupplier();
        if (StrUtil.isNotBlank(supplier)) {
            Provider provider = JSONObject.parseObject(supplier, Provider.class);
            if (provider != null) {
                excelTemplateDto.setOfflineProviderInfo(provider.getNickName() + "(NO." + provider.getProviderId() + ")");
            } else {
                excelTemplateDto.setOfflineProviderInfo("未注册");
            }
        }
        // 处理团长信息
        Provider onlineProvider = detailsDto.getOnlineProvider();
        excelTemplateDto.setOnlineProviderInfo(onlineProvider != null ? onlineProvider.getNickName() + "(NO." + onlineProvider.getProviderId() + ")" : "未注册");
        return excelTemplateDto;
    };

    /**
     * 批量发货模板
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @SuperBuilder
    public static class ShipmentTemplateDTO {
        @Excel(name = "交易时间")
        private String joinTime;
        @Excel(name = "订单编号")
        private String orderId;
        @Excel(name = "商品名称")
        private String goodsName;
        @Excel(name = "发货链接")
        private String shippingLink;
        @Excel(name = "商品规格")
        private String specification;
        @Excel(name = "玫丽价")
        private String unitPrice;
        @Excel(name = "供货价")
        private BigDecimal supplyPrice = BigDecimal.ZERO;
        @Excel(name = "实际供货价")
        private BigDecimal realSupplyPrice;
        @Excel(name = "购买数量")
        private String buyQuantity;
        @Excel(name = "实付金额")
        private String payAmount;
        @Excel(name = "订单备注")
        private String orderRemarks;
        @Excel(name = "收货人")
        private String consigneeName;
        @Excel(name = "手机号")
        private String consigneePhoneNum;
        @Excel(name = "收货地址")
        private String consigneeAddress;
        @Excel(name = "物流公司")
        private String courierName;
        @Excel(name = "物流单号")
        private String courierNumber;
    }

    public Function<GroupBuyingSub, ShipmentTemplateDTO> toShipmentTemplateDTO = (groupBuyingSub) -> {
        if (groupBuyingSub == null) {
            return null;
        }
        ShipmentTemplateDTO shipmentTemplateDTO = new ShipmentTemplateDTO();
        BeanUtils.copyProperties(groupBuyingSub, shipmentTemplateDTO);
        // 拆分收货地址
        String address = groupBuyingSub.getAddress();
        JSONObject addressObj = new JSONObject();
        if (StrUtil.isNotBlank(address)) {
            addressObj = JSONObject.parseObject(address);
        }
        if (!addressObj.isEmpty()) {
            shipmentTemplateDTO.setConsigneeName(addressObj.getString("Name"));
            shipmentTemplateDTO.setConsigneePhoneNum(addressObj.getString("PhoneNum"));
            // 处理收获地址
            String streetVillage = addressObj.getString("StreetVillage");
            int location = streetVillage.indexOf('-');
            String consigneeAddress = "";
            if (StringUtils.isNotBlank(streetVillage) && location != -1) {
                consigneeAddress = addressObj.getString("Region") + "\t" + streetVillage.substring(0, location) + addressObj.getString("Address");
            } else {
                consigneeAddress = addressObj.getString("Region") + "\t" + streetVillage + addressObj.getString("Address");
            }
            shipmentTemplateDTO.setConsigneeAddress(consigneeAddress); // 收货地址
        }
        return shipmentTemplateDTO;
    };

    /**
     * 导入真实供货价模板
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @SuperBuilder
    public static class SupplyPriceTemplateDTO {
        @Excel(name = "订单编号")
        private String orderId;
        @Excel(name = "交易时间")
        private String joinTime;
        @Excel(name = "商品名称")
        private String goodsName;
        @Excel(name = "发货链接")
        private String shippingLink;
        @Excel(name = "商品规格")
        private String specification;
        @Excel(name = "玫丽价")
        private String unitPrice;
        @Excel(name = "供货价")
        private BigDecimal supplyPrice = BigDecimal.ZERO;
        @Excel(name = "实际供货价")
        private BigDecimal realSupplyPrice;
    }

    public Function<GroupBuyingSub, SupplyPriceTemplateDTO> toSupplyPriceTemplateDTO = (groupBuyingSub) -> {
        if (groupBuyingSub == null) {
            return null;
        }
        SupplyPriceTemplateDTO supplyPriceTemplateDTO = new SupplyPriceTemplateDTO();
        BeanUtils.copyProperties(groupBuyingSub, supplyPriceTemplateDTO);
        return supplyPriceTemplateDTO;
    };


    /**
     * 团购销售佣金
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @SuperBuilder
    public static class SalesCommissionDTO{
        @ApiModelProperty(value = "订单id")
        private String id;
        @ApiModelProperty(value = "主文档ID")
        private String mainDocunid;
        @ApiModelProperty(value = "参与者id")
        private String partnerId;
        @ApiModelProperty(value = "支付订单ID")
        private String orderId;
        @ApiModelProperty(value = "订单状态：已付款、已发货、已完成、已退款；(默认已付款)")
        private String orderStatus;
        @ApiModelProperty(value = "支付金额")
        @Builder.Default
        private BigDecimal payAmount = BigDecimal.ZERO;
        @ApiModelProperty(value = "消费者分享报酬")
        @Builder.Default
        private BigDecimal consumerShareReward = BigDecimal.ZERO;
        @ApiModelProperty(value = "线上服务商分享报酬")
        @Builder.Default
        private BigDecimal foremanReward = BigDecimal.ZERO;
        @ApiModelProperty(value = "团销报酬")
        @Builder.Default
        private BigDecimal groupPinReward = BigDecimal.ZERO;
        @ApiModelProperty(value = "钱包抵扣金额")
        @Builder.Default
        private BigDecimal deductionAmount = BigDecimal.ZERO;
    }
}

